﻿using System;
using System.Reflection;
using System.Web.UI;
using Axial.Reflection;
using Axial.DOM;
using System.Linq;
using System.Web.Services;
using System.Collections.Generic;
using System.Text;

[assembly: WebResourceAttribute("Axial.PageMethod.js", "text/javascript")]

namespace Axial
{
	public class WFServerScript : Control
	{
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(WFServerScript), "PageMethod.js"))
				Page.ClientScript.RegisterClientScriptInclude(typeof(WFServerScript), "PageMethod.js",
					Page.ClientScript.GetWebResourceUrl(GetType(), "Axial.PageMethod.js"));

			IEnumerable<MethodInfo> methods = Page.GetType().BaseType.GetMethods(BindingFlags.Public | BindingFlags.Static)
				.Where(mi => mi.GetCustomAttributes(typeof(WebMethodAttribute), false).Length > 0);

			foreach (MethodInfo method in methods)
			{
				if (Page.ClientScript.IsClientScriptBlockRegistered(typeof(WFServerScript), method.Name))
					return;
				var parameters = method.GetParameters().Select(p => p.Name);
				var withCallbacks = parameters.Concat(new string[] { "onSuccess", "onFailure" }).ToArray();

				string[] jsObjectProperties = parameters.Select(p => string.Format("\"{0}\":{0}", p)).ToArray();
				string jsObject = "{" + string.Join(",", jsObjectProperties) + "}";

				JSWriter code = new JSWriter();
				code.AddStatement(string.Format("Axial.CallPageMethod('{0}', {1}, onSuccess, onFailure)", method.Name, jsObject));

				JSWriter writer = new JSWriter();
				writer.AddPrivateFunction(method.Name, withCallbacks.ToArray(), code);
				Page.ClientScript.RegisterClientScriptBlock(typeof(WFServerScript), method.Name, writer.ToString(), true);
			}
		}
	}
}
